package cn.wolfcode.luowowo.mgrsite.web.listener;

import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.util.RedisKeys;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.common.util.BeanUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import java.util.List;

/**
 *  为何要数据初始化?
 */
//@Component
public class RedisDataInitListener implements ApplicationListener<ContextRefreshedEvent> {
    //ContextRefreshedEvent 容器启动或者重新加载时触发时间

    @Reference
    private IStrategyDetailService detailService;
    @Reference
    private IStrategyStatisRedisService strategyStatisRedisService;

    //当容器启动时,执行这个方法
    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        /*//目的:将数据初始化到redis中的vo对象中
        System.out.println("--初始化开始--");
        //获取攻略对象
        List<StrategyDetail> details = detailService.list();
        *//*for (StrategyDetail detail : details) {
            System.out.println(detail);
        }*//*
        StrategyStatisVO vo = null;
        for (StrategyDetail detail : details) {
            if (strategyStatisRedisService.isStatisVOExist(detail.getId())){
                continue;
            }
            //创建vo对象
            vo = new StrategyStatisVO();
            BeanUtil.copyProperties(vo,detail);
            vo.setDestId(detail.getDest().getId());
            vo.setDestName(detail.getDest().getName());
            vo.setStrategyId(detail.getId());
            strategyStatisRedisService.setStatisVO(vo);
        }
        System.out.println("--初始化结束--");*/


        List<StrategyDetail> details = detailService.list();

        System.out.println("--热门推荐初始化开始--");
        for (StrategyDetail detail : details) {
            if(strategyStatisRedisService.isZSetStatisVOExist(RedisKeys.STRATEGY_ZSET_SORT_HOT.getPrefix(),detail.getId())){
                continue;
            }
            //热门(浏览数+评论数)
            int num = detail.getViewnum() + detail.getReplynum();
            strategyStatisRedisService.addHotScore(detail.getId(),num);
        }
        System.out.println("--热门推荐初始化结束--");

        System.out.println("--国内外推荐初始化开始--");
        for (StrategyDetail detail : details) {
            if(strategyStatisRedisService.isZSetStatisVOExist(RedisKeys.STRATEGY_ZSET_SORT_COMMEND.getPrefix(),detail.getId())){
                continue;
            }
            //国内外推荐(收藏数+点赞数)
            int num = detail.getFavornum() + detail.getThumbsupnum();
            strategyStatisRedisService.addCommendScore(detail.getId(),num);
        }
        System.out.println("--国内外推荐初始化结束--");
    }
}
